package 集合.IteratorExamples;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

class ReversibleArrayList<T> extends ArrayList<T> {
	public ReversibleArrayList(Collection<T> collection) {
		super(collection);
	}

	public Iterable<T> reversed() {
		return new Iterable<T>() {
			@NotNull
			@Override
			public Iterator<T> iterator() {
				return new Iterator<T>() {
					int current = size() - 1;

					@Override
					public boolean hasNext() {
						return current > -1;
					}

					@Override
					public T next() {
						return get(current--);
					}

					@Override
					public void remove() {
						throw new UnsupportedOperationException();
					}
				};
			}
		};
	}
}

public class AdapterMethodIdiom {
	public static void main(String[] args) {
		ReversibleArrayList<String> rals = new ReversibleArrayList<String>(Arrays.asList(" to be or not to be".split(" ")));
		for (String ral : rals) {
			System.out.print(ral + " ");
			System.out.println();
		}
		for (String s : rals.reversed()) {
			System.out.print(s + " ");
		}
	}
}
